const api = require('../../utils/api.js');
const app = getApp();
const utils = require('../../../ws_micro_shop/utils/utils.js');
const order = require('../../utils/orders.js');
let is_loading = false;
let p = 0;
let timer = null;
let cutTime = null;

Page({
  data: {
    again: false,
    status: -1,
    order_list: [],
    show_no_data_tip: false,
    hide: 1,
    qrcode: '',
    theme: app.themeData,
    showpaytypes: false,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-19.png',
      text: '暂无订单',
    },
    unit: '',
    orderid: '',
    showexpress: false,
    expresslist: [],
    express_id: '',
    currVal: '',
    isEmpty: true,
    keywords: '',
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    imgUrl: app.imgUrl,
    is_show_line: false,
    toView: 'item-1',
    admin: 'yes',
  },

  onLoad(options) {
    let that = this;
    let opts = options || {};
    app.pageOnLoad(this);
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    let pages = getCurrentPages();
    if (pages.length < 2) {
      this.setData({
        show_index: true,
      });
    }
    let isMulti =
      app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isMulti;
    this.setData({
      commentSwitch: wx.getStorageSync('store').comment_switch,
      status: opts.status || -1,
      toView: 'item' + (opts.status || -1),
      opts,
      isMulti,
      useTabbar: this.data.useTabbar && app.getTabBarStatus(),
    });
  },

  onHide() {
    timer && clearInterval(timer);
    cutTime && clearInterval(cutTime);
  },
  onUnload() {
    timer && clearInterval(timer);
    cutTime && clearInterval(cutTime);
  },

  onShow() {
    let { status, opts: { fromHome }} = this.data;
    is_loading = false;
    p = 1;
    this.setData({
      is_show_line: false,
      showexpress: false,
    });
    this.loadOrderList(status);
    if (Number(fromHome) === 1) {
      let pages = getCurrentPages(); //  获取页面栈
      let prevPage = pages[pages.length - 2]; // 上一个页面
      prevPage.setData({
        fromHome: true,
      });
    }
  },

  switchList(e) {
    cutTime && clearInterval(cutTime);
    let data = e.currentTarget.dataset;
    let { lastStatus } = this.data;
    if (Number(lastStatus) === Number(data.status)) return;
    is_loading = false;
    p = 1;
    this.setData({
      // currVal: '',
      is_show_line: false,
      lastStatus: data.status,
      toView: 'item' + data.status,
    });
    this.loadOrderList(data.status);
  },

  loadOrderList(st, k = '') {
    let status = st;
    if (!status) {
      status = -1;
    }
    let _this = this;
    _this.setData({
      status,
      toView: 'item' + status,
      lastStatus: status,
    });
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    this.getList();
  },
  getList() {
    let _this = this;
    if (p == 1) {
      _this.setData({
        order_list: [],
      });
    }
    app.ws_micro_shoprequest({
      // url: api.order.list,
      url: api.order.listNew_all,
      // url: api.order.listNew,
      data: {
        status: _this.data.status,
        page: p,
        keywords: _this.data.keywords,
      },
      success: function (res) {
        if (res.code === 0) {
          let order_list = _this.data.order_list.concat(res.data.list);
          _this.setData({
            order_list,
            show_no_data_tip: order_list.length === 0,
            is_show_line: res.data.list.length === 0,
            // pay_type_list: res.data.pay_type_list,
          }, () => {
            // timediff 剩余总秒数 cd 20200117
            _this.countDown();
          });
        }
        p++;
      },
      complete: function () {
        wx.hideLoading();
        is_loading = false;
      },
    });
  },
  countDown() {
    let _this = this;
    function calc() {
      let { order_list } = _this.data;
      for (let i in order_list) {
        if ({}.hasOwnProperty.call(order_list, i)) {
          if (order_list[i].timediff && order_list[i].timediff > 0) {
            order_list[i].timediff--;
            order_list[i].tipTime = utils.getLeaveTime(order_list[i].timediff);
          } else {
            order_list[i].tipTime = 0;
          }
          _this.setData({
            order_list,
          });
        }
      }
    }
    cutTime = setInterval(function () {
      calc();
    }, 1000);
  },
  onReachBottom() {
    if (is_loading || this.data.is_show_line) {
      return;
    }
    is_loading = true;
    this.getList();
  },
  
  showPayType(e) {
    let that = this;
    let { id, type, discount, paytype, payment } = e.currentTarget.dataset;
    let t = Number(type) === 2 ? 3 : 0;
    app.getSubscribeMessage(t).then(res => {
      that.setData({
        orderID: id,
        orderType: type,
        discountId: Number(discount) === 1 ? payment : -1,
      });
      if (paytype != undefined) {
        that.setData({
          pay_type_list: paytype,
          showpaytypes: true,
        });
      } else {
        that.getPayType(e);
      }
    });
  },

  getPayType(e) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.order.pay_type,
      data: {
        order_id: e.currentTarget.dataset.id,
      },
      complete: function() {
        wx.hideLoading();
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            pay_type_list: res.data,
            showpaytypes: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
  },

  disabledClick() {},

  hidePayType() {
    this.setData({
      showpaytypes: false,
    });
  },

  orderPay(e) {
    order.orderPay(e, this.data.orderID, this.data.orderType);
    this.setData({
      showpaytypes: false,
    });
  },

  orderRevoke(e) {
    let { id, type, msg, is_pay, order_cancel } = e.currentTarget.dataset;
    let _this = this;
    order.orderRevoke(id, msg, type, order_cancel, res => {
      if (res.confirm) {
        p = 1;
        let status = Number(is_pay) === 1 ? _this.data.status : 5;
        _this.setData({
          toView: 'item' + status,
          lastStatus: status
        });
        _this.loadOrderList(status);
      }
    });
  },

  orderConfirm(e) {
    let { id, type } = e.currentTarget.dataset;
    let _this = this;
    order.orderConfirm(id, type, res => {
      if (res.code === 0) {
        p = 1;
        _this.setData({
          toView: 'item6',
          lastStatus: 6
        });
        _this.loadOrderList(6);
      }
    });
  },

  orderQrcode(e) {
    let _this = this;
    let order_list = _this.data.order_list;
    let index = e.currentTarget.dataset.index;
    let orderId = order_list[index].order_id;
    let orderNo = order_list[index].order_no;
    let type = order_list[index].o_type;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    if (_this.data.order_list[index].offline_qrcode) {
      _this.setData({
        hide: 0,
        qrcode: _this.data.order_list[index].offline_qrcode,
      });
      wx.hideLoading();
    } else {
      order.orderQrcode(orderNo, orderId, type, res => {
        if (res) {
          _this.setData({
            hide: 0,
            qrcode: res.data.url,
          });
          if (timer) {
            timer && clearInterval(timer);
          }
          _this.Loop(orderId, type);
        }
      });
    }
  },

  quickAddCart(e) {
    order.quickAddCart(e);
  },

  hide() {
    timer && clearInterval(timer);
    this.setData({
      hide: 1,
    });
  },

  onNavigate(e) {
    let param = e.currentTarget.dataset;
    app.ws_micro_shop_navigate(param);
  },

  Loop(id, type) {
    let _this = this;
    timer = setInterval(function() {
      app.ws_micro_shoprequest({
        url: api.default.orderClerk,
        data: {
          order_id: id,
          type: type == 1 ? 'default' : type == 2 ? 'pt' : 'ms',
        },
        success: function(res) {
          if (res.code === 0) {
            if (Number(res.data) === 1) {
              timer && clearInterval(timer);
              _this.setData({
                hide: 1,
              });
              _this.loadOrderList(_this.data.status);
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
            });
          }
        },
      });
    }, 2000);
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  showExpressList(e) {
    let { idx, orderid, iscycle, type } = e.currentTarget.dataset;
    if (type > 1) {
      app.util.navigateTo('/ws_micro_shop/pages/express-detail/express-detail', {
        id: orderid,
        type: type == 2 ? 'pt' : 'miaosha',
      });
      return;
    }
    let orderlist = this.data.order_list;
    let expresslist = orderlist[idx].express;
    if (Number(iscycle) === 1) {
      app.util.navigateTo(
        '/ws_micro_shop/pages/cycle-purchase/cycle-purchase',
        {
          order_id: orderid,
        }
      );
    } else {
      this.setData({
        expresslist,
        orderid,
        showexpress: expresslist.length > 0,
        express_id: '',
      });
    }
  },

  catchTap() {
    // it`s necessary
  },

  cancelCheck() {
    this.setData({
      showexpress: false,
      express_id: '',
    });
  },

  chooseExpressId(e) {
    this.setData({
      express_id: e.detail.value,
    });
  },

  sureCheck() {
    let { express_id, orderid } = this.data;
    if (!express_id) {
      wx.showToast({
        title: '请选择快递单号',
        icon: 'none',
      });
      return;
    }
    app.util.navigateTo('/ws_micro_shop/pages/express-detail/express-detail', {
      id: orderid,
      type: 'goods',
      express_id,
    });
  },

  deleteOrder(e) {
    let that = this;
    let { idx } = e.currentTarget.dataset;
    let orderlist = that.data.order_list;
    order.deleteOrder(e, res => {
      if (res) {
        orderlist.splice(idx, 1);
        that.setData({
          order_list: orderlist,
          show_no_data_tip: orderlist.length === 0,
        });
      }
    });
  },

  inputChange(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      currVal: val,
    });
  },

  clearTxt() {
    let status = this.data.status;
    is_loading = false;
    p = 1;
    this.setData({
      currVal: '',
      keywords: '',
      order_list: [],
      isEmpty: true,
    });
    this.loadOrderList(status);
  },

  searchTxt(keyword) {
    let keywords = keyword;
    let status = this.data.status;
    is_loading = false;
    p = 1;
    this.setData({
      keywords,
      order_list: [],
    });
    this.loadOrderList(status, keywords);
  },

  searchSure() {
    let keyword = this.data.currVal.trim();
    this.searchTxt(keyword);
  },

  showMoreOpr(e) {
    let { orderid } = e.currentTarget.dataset;
    let { order_list } = this.data;
    for (let i in order_list) {
      if (Number(orderid) === Number(order_list[i].order_id)) {
        order_list[i].showmorebtn = !order_list[i].showmorebtn;
      } else {
        order_list[i].showmorebtn = false;
      }
    }
    this.setData({
      order_list,
    });
  },
  goDetail(e) {
    wx.showLoading({
      title: '正在跳转...',
    });
    let { id, type, status, refund } = e.currentTarget.dataset;
    let url = status == 4 ? '/ws_micro_shop/pages/order-refund-detail/order-refund-detail?entry=' + (type == 1 ? 'default' : type == 3 ? 'ms' : 'pt') + '&id=' + refund : type == 1 ? '/ws_micro_shop/pages/order-detail/order-detail?id=' + id : type == 3 ? '/ws_micro_shop_ms/pages/miaosha/order-detail/order-detail?id=' + id : '/ws_micro_shop_pt/pages/pt/order-details/order-details?id=' + id;
    wx.navigateTo({
      url: url,
    });
  },
  refund(e) {
    let { type } = e.currentTarget.dataset;
    let entry = Number(type) === 1 ? 'default' : (Number(type) === 2 ? 'pt' : 'ms');
    app.util.navigateTo('/ws_micro_shop/pages/order-refund/order-refund', {
      id: e.currentTarget.dataset.id,
      entry: entry,
    });
  },
  ping(e) {
    order.ping(e);
  },
});
